<script>
import Vue from 'vue';
import department from './department/department';
import commonList from '../components/commonList'
import leftTreeLayout from '../components/leftTreeLayout'
import OnlyOneNodeSelectPerson from 'party_fe_component/src/components/tree/orgTree/onlyOneNodeSelectPerson';
import OrgTreeDialog from 'party_fe_component/src/components/tree/orgTree/orgTreeDialog';
import { PageTypes, ErrorCodes } from '../common/const';
import { getOrgConfig, loadParentLabel, orgBatchMove } from '../common/api';

Vue.component('department', department);

export default {
    extends: commonList,
    mixins: [require('../common/orgTagMixin').default],
    data () {
        return {
            mappingFields: {
                department: "department_name"
            }
        }
    },
    methods: {
        onCloseComponent() {
            this.showComponent = false;
            this.componentName = '';
        },
        // 根据appId加载formName
        loadFormName() {
            return getOrgConfig().then(({ data = {} } = {}) => {
                const { formName, orgLable, parentOrgLable = [ '' ] } = data;
                this.formName = formName;
                this.orgLabel = orgLable;
                this.parentOrgLable = parentOrgLable;
                if (!this.formName) {
                    console.error('formName获取失败')
                }
            })
        },
        loadParentLabels () {
            const { parentId, currentNodeName, parentOrgLable, labelIdList } = this;
            if (parentOrgLable && parentOrgLable.length && parentOrgLable[0] !== '') {
                if (labelIdList && labelIdList.length && labelIdList[0] !== '') {
                    if (labelIdList[0] != parentOrgLable[0]) {
                        loadParentLabel(parentId, [ parentOrgLable[0] ]).then(({ data = [] } = {}) => {
                            if (data.length) {
                                const parentOrg = data[0];
                                const { id, name } = parentOrg;
                                this.parentOrgId = id;
                                this.parentOrgName = name;
                            } else {
                                this.parentOrgId = '';
                                this.parentOrgName = '';
                            }
                            this.completeReady = true;
                        });
                    } else {
                        this.parentOrgId = parentId;
                        this.parentOrgName = currentNodeName;
                        this.completeReady = true;
                    }
                } else {
                    this.completeReady = true;
                }
            } else {
                this.completeReady = true;
            }
        },
        loadListBy(page, searchData, isSearch) {
            this.loading = true
            var { searchGroupType, ...data } = searchData || {}
            var pars = {
                data,
                parent_group_id: this.parentId,
                recursive: false,
                searchGroupType,
            }

            if (!isSearch) {
                pars.page = page;
            }

            return this.$x.post('/orginfo/orgOperation/orgQueryPage', pars, { maskOptions: false })
                .then(({ data = [], page } = {}) => {
                    this.dataList = data;

                    if (page) {
                        this.pageInfo = page;
                    }

                    this.total = page && page.total;
                })
                .finally(t => {
                    this.loading = false;
                    this.reloadSubs();
                })
        },
        addItem() {
            this.goEditRoute('/org/add', PageTypes.FormAdd);
        },
        editItem() {
            this.goEditRoute('/org/edit', PageTypes.FormEdit, this.currentNodeId, this.parentNodeId);
        },
        department() {
            this.showComponent = true;
            this.componentName = 'department';
        },
        _rowEdit(row) {
            this.goEditRoute('/org/edit', PageTypes.FormEdit, row.id);
        },
        _rowView(row) {
            this.goEditRoute('/org/view', PageTypes.FormView, row.id);
        },
        // 移动操作
        _rowMove({ id }) {
            this.doBatchMove([ id ]);
        },
        doBatchMove(ids = []) {
            this.$refs.moveDlg.showOrgDialog().then((selects) => {
                const target = selects[0].id;

                const hasSame = ids.find(id => id === target) != null;
                if (hasSame) {
                    return this.$x.toast.warning('移动节点和选择节点相同，请重新选择');
                }

                this.loading = true;
                orgBatchMove(ids, target).then(({ errcode = ErrorCodes.Success, errmsg = '操作成功' }) => {
                    this.loading = false;
                    if (errcode === ErrorCodes.Success) {
                        this.$x.toast.success(errmsg);
                        this.loadList();
                        this.reloadSubs();
                    } else {
                        this.$x.toast.error(errmsg);
                    }
                }).catch(() => {
                    this.loading = false;
                    this.$x.noop();
                });
            });
        },
        goEditRoute(path, pageType, id, parentNodeId) {
            const { labelIds } = this;
            var pars = {
                pageType,
                formName: this.formName,
                parentId: parentNodeId || this.parentId,
                currentNodeId: id,
                parentOrgId: this.parentOrgId,
                parentOrgName: this.parentOrgName,
                parentNodeId: this.parentNodeId,
                // parentName: this.formName === 'OrgParty' ? this.rootOrg.name : this.parentOrg.name,
                parentName: this.parentOrg.name,
                orgLabel: labelIds && labelIds.length && labelIds[0]
            }
            if (id) pars.id = id
            if (pageType === PageTypes.FormAdd) pars.rootId = this.rootId
            this.$router.push(this.$x.toQueryUrl(path, pars))
        },
        // 批量移动
        _batBatMove(rows) {
            this.doBatchMove(rows.map(row => row.id));
        },
        _batBatDelete(rows) {
            /* eslint-disable-next-line */
            var h = this.$createElement
            var msg = (
                <div>
                    <div>{'请确定是否要删除' + this.fgObjTitle + '？'}</div>
                    <br/>
                    <small style="font-weight:normal">{this.fgTexts.confirmSubOrg
                    || '如果该' + this.fgObjTitle + '下，存在人员或子组织，则无法删除。'}</small>
                </div>
            )
            this.$x.confirm(msg, '删除' + this.fgObjTitle, {
                confirmButtonText: this.fgTexts.delete || '删除',
                cancelButtonText: this.fgTexts.cancel || '取消',
                type: 'warning',
            }).then(async t => {
                var idList = rows.map(row => row.id)
                var pars = {
                    idList,
                    parent_group_id: this.parentId,
                }
                await this.$x.delete('/orginfo/orgOperation/orgDelete', pars)
                this.$x.toast.success(this.fgTexts.deleteSuccess || '删除成功')
                this.loadList()
                this.reloadSubs()
            }).catch(this.$x.noop)
        },
        _batImport() {
            var pars = {
                rootId: this.rootId,
                parentId: this.parentId,
                formName: this.formName,
                objTitle: this.fgObjTitle,
                parentOrgId: this.parentOrgId,
                parentOrgName: this.parentOrgName,
            }
            this.$router.push(this.$x.toQueryUrl('/org/import', pars))
        },
        _batExport() {
            var pars = {
                parent_group_id: this.parentId,
            }
            this.$x.post('/orginfo/orgFile/excelExport', pars).then(res => {
                this.showImExportMsg(false)
            })
        },

        async saveSort() {
            var pars = {
                businessType: this.$x.tokenUtil.businessType,
                groupList: this.sortData.map((id, index) => ({ id, index })),
                parentId: this.parentId,
                spId: this.$x.tokenUtil.spId,
            }
            await this.$x.post('/org/org/v2/update-group-position', pars)
            this.$x.toast.success(this.fgTexts.saveSuccess || '保存成功!')
            this.stopSortAndReload()
            this.reloadSubs() // 排序后需要刷新树
        },

        async _rowSetAdmin(row) {
            var currentOrg = {
                isOrg: true,
                icon: '',
                configedWhiteList: false,
                id: row.id,
                memberId: null,
                name: row.group_name,
                parentGroup: null,
                parentId: '0',
                permission: true,
                subGroups: null,
                childNodes: [],
                view: false
            }

            var pars = {
                businessType: this.$x.tokenUtil.businessType,
                groupId: row.id,
                spId: this.$x.tokenUtil.spId
            }
            var res = await this.$x.post('{org}/position/admin/query', pars)
            var curAdminData = res.data || {}
            // var { page, memberIds, updateTime, createTime, bid, ...curAdminData } = t
            curAdminData.businessType = pars.businessType

            var members = (curAdminData.members || [])
            this.$refs.setAdminDlg.showOrgDialog([currentOrg], members)
                .then(async selectedDatas => {
                    curAdminData.members = selectedDatas.map(nodeData => ({
                        contactId: nodeData.id,
                        memberId: nodeData.memberId,
                        name: nodeData.name
                    }))
                    await this.$x.post('{org}/position/admin/save', curAdminData)
                    this.$x.toast.success('设置成功!')
                })
                .catch(this.$x.noop);
        },

        reloadSubs() {
            this.$refs.leftTree1.tree.reloadSubs(this.parentOrg.id)
        },
        changeList(from) {
            this.loadList()
            this.reloadSubs() // 新增和编辑，都需要刷新树
        },
        getTreeParams() {
            const uiSet = this.uiSet;
            const { dependOrgTag, orgTag } = uiSet;

            const orgTags = [];
            const parentOrgLable = this.parentOrgLable || [ '' ];

            if (orgTag !== '') {
                orgTags.push(orgTag);
            }

            if (dependOrgTag !== '') {
                orgTags.push(dependOrgTag);
            }

            let rootPermission = false;
            if (parentOrgLable.length) {
                const parent = parentOrgLable[0];
                rootPermission = parent === '';

                if (parent !== '') {
                    orgTags.push(parent);
                }
            }

            const enableIds = [];

            if (this.orgLabel) {
                enableIds.push(this.orgLabel);
            }

            if (this.parentOrgLable) {
                enableIds.push(this.parentOrgLable);
            }

            return {
                switchOrg: !!dependOrgTag,
                dependOrgTag,
                orgTag,
                orgTags: Array.from(new Set(orgTags)),
                dependOrgTags: [Array.from(new Set([dependOrgTag, orgTag]))],
                rootPermission,
                enableIds
            }
        }
    },

    render(h) {
        if (!this.configReady || !this.uiSet) {
            return;
        }

        const { switchOrg, rootPermission, dependOrgTag, dependOrgTags, orgTag, orgTags, enableIds } = this.getTreeParams();

        // 父组件模板渲染
        var superRendered = this.showComponent ? '' : this.$options.extends.render.apply(this, arguments)
        var setAdminDialog = (
            <OnlyOneNodeSelectPerson
                ref="setAdminDlg"
                show-member={true}
                checkType="member"
                bizAppId={this.$x.tokenUtil.appId}
                searchText={this.fgObjTitle}
                onlyLoadPerson={true}
                isMember={undefined}
                required={false}
            >
            </OnlyOneNodeSelectPerson>)

        var moveDialog = (
            <OrgTreeDialog
                ref="moveDlg"
                enableIdList={ enableIds }
                singleCheck={true}
                permission={false}>
            </OrgTreeDialog>
        );

        return (
            <leftTreeLayout
                ref="leftTree1"
                orgId={this.currentNodeId}
                orgTag={orgTag}
                isDistrict={this.isDistrict}
                showComponent={this.showComponent}
                componentName={this.componentName}
                hideLeft={this.isSubRouter}
                onNodeClick={this.onNodeClick}
                onRootChanged={this.changeRoot}
                fgTexts={this.fgTexts}
                selectedRoot={true}
                orgTags={orgTags}
                switchOrg={switchOrg}
                rootPermission={rootPermission}
                dependOrgTags={dependOrgTags}
                onCloseComponent={this.onCloseComponent}
            >
                <header slot="treeHead" class="tree-head">{this.fgTexts.orgStruct || '组织架构'}</header>
                {superRendered}{setAdminDialog}{moveDialog}
            </leftTreeLayout>
        )
    },
    watch: {
        parentIdReady (newVal) {
            if (newVal) {
                this.loadParentLabels();
            }
        },
        parentId (newVal) {
            this.completeReady = false;
            this.loadParentLabels();
        }
    },
    computed: {
        isSubRouter() {
            return this.$route.path !== '/org/list';
        },
        fgObjTitle() {
            return this.fgTagNames[this.uiSet && this.uiSet.orgTag] || '组织';
        },
        showActionDepartment () {
            return this.completeReady && this.showRowOutAction('Department');
        },
        showActionEdit () {
            return this.completeReady && this.showRowOutAction('Current');
        },
        showActionAdd () {
            return this.completeReady && Object.keys(this.parentOrg).length !== 0 && this.showRowOutAction('Subordinate');
        },
        actionAddText() {
            //子类可覆盖
            return '新建下级' + this.fgObjTitle;
        },
        actionEditText() {
            return '编辑本' + this.fgObjTitle;
        }
    }
}
</script>
